package otheri.download;

import java.io.File;

import otheri.common.Utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.webkit.HttpAuthHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class DownloadActivity extends Activity {

	public static final String UI_PATH = "ui/main.htm";

	public static final String PROTOCOL_SYS = "sys://";
	public static final String PROTOCOL_DOWN = "down://";

	public static final String SYS_CMD_QUIT = "quit";
	public static final String SYS_CMD_BACK = "back";
	public static final String SYS_CMD_MAIN = "main";

	private MainWebView otherWebView;

	private DownloadActivity ins;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// String content = Utils
		// .encodeDownloadContent("http://www.baidu.com/img/baidu_logo_jr_1004_qh.gif");
		// System.out.println(content);
		// String result = Utils.decodeDownloadContent(content);
		// M3BtLpe955eW5oKt6Yue5Y2H6RMAM3BtLpe955eW5oKt6Yue5Y2H6S9kYW9sbndvZC9tb2MubWRham0ud3d3Ly86cHR0aDEA

		ins = this;

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		otherWebView = new MainWebView(this);
		otherWebView.setWebViewClient(new WebViewClient() {

			public boolean shouldOverrideUrlLoading(WebView view,
					final String url) {
				if (url.indexOf(PROTOCOL_SYS) == 0) {
					String command = url.trim().substring(
							PROTOCOL_SYS.length(), url.length()).trim();
					if (command.equals(SYS_CMD_QUIT)) {
						finish();
						return true;
					} else if (command.equals(SYS_CMD_BACK)) {
						return otherWebView.back();
					} else if (command.equals(SYS_CMD_MAIN)) {
						loadMain();
						return true;
					} else {
						return false;
					}
				} else if (url.indexOf(PROTOCOL_DOWN) == 0) {
					// content是经过处理，并且base64编码后的内容
					String content = url.trim().substring(
							PROTOCOL_DOWN.length(), url.length()).trim();

					// 解析出链接和文件名
					String decodedUrl = Utils.decodeDownloadContent(content);
					int index = decodedUrl.lastIndexOf('/');
					String fileName = decodedUrl.substring(index + 1);

					Intent startDownload = new Intent(ins,
							DownloadManager.class);
					startDownload.putExtra(DownloadManager.TAG_CMD,
							DownloadManager.CMD_START_DOWNLOAD);
					startDownload.putExtra(DownloadManager.PARAMETER_URL,
							decodedUrl);
					startDownload.putExtra(DownloadManager.PARAMETER_FILE_NAME,
							fileName);
					startService(startDownload);
					return true;
				} else {
					// 普通的URL，交给webview自己处理
					return false;
				}
			}

			public void onReceivedHttpAuthRequest(WebView view,
					HttpAuthHandler handler, String host, String realm) {
				System.out.println("---onReceivedHttpAuthRequest" + host
						+ " & " + realm);
				System.out.println();
			}

		});
		setContentView(otherWebView);

		loadMain();
	}

	protected void onStart() {
		super.onStart();

		// 如果不存在下载目录，则创建
		File root = new File(DownloadManager.SDCARD_ROOT);
		if (!root.exists()) {
			if (!root.mkdir()) {
				// 创建失败，可能是没有SD卡，返回错误广播并退出Service

				return;
			}
		}

		// 启动DownloadService服务
		Intent startDownloadService = new Intent(ins, DownloadManager.class);
		startDownloadService.putExtra(DownloadManager.TAG_CMD,
				DownloadManager.CMD_START_SERVICE);
		startService(startDownloadService);
	}

	protected void onRestart() {
		super.onRestart();
	}

	protected void onResume() {
		super.onResume();
	}

	protected void onPause() {
		super.onPause();
	}

	protected void onStop() {
		super.onStop();
	}

	protected void onDestroy() {
		super.onDestroy();
	}

	private void loadMain() {
		// 清空webview
		otherWebView.clearCache(true);
		otherWebView.clearHistory();

		// 如果没有下载过，则使用assets里的默认界面
		// 可以将新的界面通过网络更新到files/ui目录下
		File ui = new File("/data/data/otheri.download/files/" + UI_PATH);
		if (ui.exists()) {
			// 下载到的UI
			Utils.println("load ui from files");
			otherWebView.loadUrl("file:///data/data/otheri.download/files/"
					+ UI_PATH);
		} else {
			// 系统默认的UI
			Utils.println("load ui from assets");
			otherWebView.loadUrl("file:///android_asset/" + UI_PATH);
		}
	}

	private void testUIdownload() {

	}

}